<template>
  <a-modal
    v-model:open="visible"
    title="删除知识库"
    :width="480"
    :confirm-loading="isDeleting"
    ok-text="确认删除"
    cancel-text="取消"
    ok-type="danger"
    @ok="handleConfirm"
    @cancel="handleCancel"
  >
    <div class="delete-knowledge-content">
      <div class="warning-icon">
        <ExclamationCircleOutlined style="font-size: 48px; color: #ff4d4f;" />
      </div>

      <div class="warning-text">
        <h3>确认删除知识库？</h3>
        <p v-if="knowledgeBase">
          您即将删除知识库 <strong>"{{ knowledgeBase.name }}"</strong>
        </p>
        <p class="warning-message">
          删除后将无法恢复，请谨慎操作！
        </p>
      </div>

      <div v-if="knowledgeBase" class="knowledge-info">
        <div class="info-item">
          <span class="label">知识库名称：</span>
          <span class="value">{{ knowledgeBase.name }}</span>
        </div>
        <div v-if="knowledgeBase.description" class="info-item">
          <span class="label">描述：</span>
          <span class="value">{{ knowledgeBase.description }}</span>
        </div>
        <div v-if="knowledgeBase.fileName" class="info-item">
          <span class="label">文件名：</span>
          <span class="value">{{ knowledgeBase.fileName }}</span>
        </div>
        <div v-if="knowledgeBase.fileSize" class="info-item">
          <span class="label">文件大小：</span>
          <span class="value">{{ formatFileSize(knowledgeBase.fileSize) }}</span>
        </div>
        <div v-if="knowledgeBase.createdAt" class="info-item">
          <span class="label">创建时间：</span>
          <span class="value">{{ formatDate(knowledgeBase.createdAt) }}</span>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { KnowledgeBaseListVO } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores/modules/auth'

// Props
interface Props {
  open: boolean
  knowledgeBase?: KnowledgeBaseListVO | null
}

// Emits
interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const isDeleting = ref(false)

// Store
const authStore = useAuthStore()

// API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top'
})

// 监听props变化
watch(() => props.open, (newVal) => {
  visible.value = newVal
})

watch(visible, (newVal) => {
  emit('update:open', newVal)
})

// 确认删除
const handleConfirm = async () => {
  if (!props.knowledgeBase?.id) {
    message.error('知识库ID不存在')
    return
  }

  isDeleting.value = true
  try {
    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    // 调用删除知识库接口
    const response = await api.deleteKnowledgeBase(props.knowledgeBase.id, {
      headers
    })

    if (response.data?.code === 0) {
      message.success('知识库删除成功！')
      console.log('知识库删除成功')

      // 触发成功事件
      emit('success')

      // 关闭弹窗
      visible.value = false
    } else {
      throw new Error(response.data?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除知识库失败:', error)
    message.error('知识库删除失败，请重试')
  } finally {
    isDeleting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  visible.value = false
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString: string): string => {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}
</script>

<style scoped>
.delete-knowledge-content {
  text-align: center;
  padding: 16px 0;
}

.warning-icon {
  margin-bottom: 16px;
}

.warning-text {
  margin-bottom: 24px;
}

.warning-text h3 {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.warning-text p {
  margin: 8px 0;
  color: #595959;
  line-height: 1.5;
}

.warning-message {
  color: #ff4d4f !important;
  font-weight: 500;
}

.knowledge-info {
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 16px;
  text-align: left;
  margin-top: 16px;
}

.info-item {
  display: flex;
  margin-bottom: 8px;
  line-height: 1.5;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  min-width: 80px;
  color: #8c8c8c;
  font-size: 14px;
}

.value {
  flex: 1;
  color: #262626;
  font-size: 14px;
  word-break: break-all;
}

.value strong {
  color: #1890ff;
}
</style>
